package list.arry;

public class Arry {

    private int size;

    private int capacity;

    private int data[];

    /**
     *
     * @param capacity 构造函数传入数组的容量capacity
     */
    public Arry(int capacity) {
        if (capacity<=0){
            capacity = 10;
        }
        this.capacity = capacity;
        data = new int[capacity];
        this.size = 0;
    }

    public Arry() {
        this(10);
    }

    public int getSize(){
        return this.size;
    }

    public int getCapacity(){
        return this.capacity;
    }

    /**
     * 数组是否为空：
     * true：size==0
     * @return
     */
    public boolean isEmpty(){
        return this.size == 0;
    }

    public void addLast(int e){
        this.addIndex(size, e);

    }

    public void addFirst(int e){
        this.addIndex(0, e);
    }

    public void addIndex(int index, int e){
        if (index < 0 || index >size){
            throw new IllegalArgumentException("index valid. require index >=0 and index <=size");
        }
        if (size == capacity){
            this.resize();
        }

        for (int i = size; i > index; i--) {
            this.data[i] = this.data[i-1];
        }
        this.data[index] = e;
        size++;
    }

    public void set(int index, int e){
        if (index < 0 || index >=size){
            throw new IllegalArgumentException("index valid. require index >=0 and index <=size");
        }
        this.data[index] = e;
    }

    public int getIndex(int index) {
        if (index<0 || index >= size){
            throw new IllegalArgumentException("index valid. require index >=0 and index <=size");
        }
        return this.data[index];
    }

    private void resize(){
        int[] newData = new int[capacity*2];
        for (int i = 0; i < size; i++) {
            newData[i] = this.data[i];
        }
    }

    public static void main(String[] args) {

        Arry arry = new Arry(5);
        System.out.println(arry.getSize());
        System.out.println(arry.getCapacity());
        arry.addLast(0);
        arry.addLast(1);
        arry.addLast(2);
        for (int i = 0; i < arry.size; i++) {
            System.out.println(arry.getIndex(i));
        }
        arry.addIndex(1,5);
        arry.addLast(4);
        for (int i = 0; i < arry.size; i++) {
            System.out.println(arry.getIndex(i));
        }
        arry.addLast(6);
        for (int i = 0; i < arry.size; i++) {
            System.out.println(arry.getIndex(i));
        }

    }


}
